﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Web.Security;
using System.Xml.Serialization;
using System.IO;
using System.Threading;
using WCF;

namespace geekmeet
{
    /// <summary>
    /// The page where usear can change account settings
    /// </summary>
    public partial class Settings : System.Web.UI.Page
    {
        GeekMeetService wcf = new GeekMeetService();
        Guid loggedInUserGUID = (Guid)Membership.GetUser().ProviderUserKey;
        ProfileComposite userProfile;

        protected void Page_Load(object sender, EventArgs e)
        {
            userProfile = wcf.GetProfile(loggedInUserGUID);

            if (!IsPostBack)
            {
                GetPremiumHistory();
                CheckPremium();
                FillDates();
                CheckVisibleState();
            }
        
            if (Request.QueryString["action"] == "ExportProfile")
                ExportProfile();

            if (Request.QueryString["action"] == "DeleteUser")
                DeleteUser();

        
        }

        /// <summary>
        /// Deletes logged in user account
        /// </summary>
        private void DeleteUser()
        {
            // path to user profile picture
            string imageDir = Server.MapPath("/images/profilePictures/" + loggedInUserGUID + ".jpg");
            
            try
            {
                bool status = wcf.DeleteUser(loggedInUserGUID);
                // If success on delete user, remove profile picture and sign out
                if (status == true)
                {
                    if (File.Exists(imageDir))
                    {
                        File.Delete(imageDir);
                    }
                    FormsAuthentication.SignOut();
                    Response.Redirect("/Default.aspx");
                }
            }
            catch (Exception ex)
            {
                Response.Write("Ett fel uppstod: " + ex.Message);
            }

        }
        
        /// <summary>
        /// Exports a profile to a XML-document using serialization
        /// </summary>
        private void ExportProfile()
        {
            //Creates path and filename based on user
            string dir = Server.MapPath("ProfileExports/");
            string fileName = userProfile.Username + "_" + DateTime.Now.ToShortDateString() + ".xml";
            string xmlSavePath = dir + fileName;
            //Creates a new filestream and opens a file
            FileStream fs = File.Open(
                        xmlSavePath,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.ReadWrite);
            try
            {
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                //Instanciates an object of the XML-serializer
                XmlSerializer ser = new XmlSerializer(userProfile.GetType(), xmlSavePath);
                //Serializes the object userProfile into XML, making the properties of the object 
                //to tags in XML.
                ser.Serialize(fs, userProfile);
                
                fs.Close();
                fs.Dispose();

                //Lets the user save or open the xml-document
                Response.ContentType = "text/xml";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName + "");
                Response.TransmitFile(Server.MapPath("ProfileExports/" + fileName));
                Response.End();


            }
            catch (Exception ex)
            {
                Response.Write("Ett fel uppstod: " + ex.Message);
            }
          
        }

        /// <summary>
        /// Displays the history of premium buys 
        /// </summary>
        private void GetPremiumHistory()
        {
            List<TransactionComposite> history = (List<TransactionComposite>) wcf.GetPremiumHistory(loggedInUserGUID);

                historyRepeater.DataSource = history;
                historyRepeater.DataBind();
        }

        /// <summary>
        /// Determines if the user is visible in searches or not, and checks proper checkbox
        /// </summary>
        private void CheckVisibleState()
        {
            if (userProfile.IsVisible)
                chkVisible.Checked = true;
            else
                chkVisible.Checked = false;
        }

        /// <summary>
        /// Checks and displays if the user is premium or not
        /// </summary>
        private void CheckPremium()
        {
            DateTime currentDate = DateTime.Now;
            DateTime premiumExpires = userProfile.PremiumExpireDate;
            bool IsPremium = userProfile.IsPremium;
            bool IsInRole = Roles.IsUserInRole("premiumuser");

            //if user is premium, print out the expiration date
            if (IsPremium && IsInRole && premiumExpires >= currentDate)
            {
                lblPremiumExpiryDate.Text = userProfile.PremiumExpireDate.ToShortDateString();
                panIsPremium.Visible = true;
            }
            else
            {
                //remove user from role if he isnt premium
                if (IsInRole)
                    Roles.RemoveUserFromRole(userProfile.Username, "premiumuser");

                panIsNotPremium.Visible = true;
            }
        }

        /// <summary>
        /// Fills the date drop downs
        /// </summary>
        private void FillDates()
        {

            // populate the month drop down
            DateTime d = new DateTime(1977, 01, 01);
            for (int month = 1; month < 13; month++)
            {
                ListItem li = new ListItem();
                li.Text = month.ToString();
                li.Value = month.ToString();
                ddlMonth.Items.Add(li);
            }
            // populate the years drop down
            DateTime startYear = DateTime.Now;
            for (int i = 0; i < 11; i++)
            {
                ListItem li = new ListItem();
                li.Text = startYear.AddYears(i).ToString("yy");
                li.Value = startYear.ToString("yyyy");
                ddlYear.Items.Add(li);
            }
        }

        protected void BtnConfirmTransaction_Click(object sender, EventArgs e)
        {
            ConfirmTransaction();
        }

        /// <summary>
        /// Confirms the transaction of premium buy 
        /// </summary>
        private void ConfirmTransaction()
        {
            //if validation ok
            if (Page.IsValid)
            {
                try
                {
                    txtFirstName.Text.ToLower();
                    txtFirstName.Text.ToLower();
                    Convert.ToDecimal(txtCardNumber.Text);
                    Convert.ToDecimal(txtCVV.Text);

                    bool success = wcf.CreateTransaction(txtCardNumber.Text, loggedInUserGUID);

                    if (success)
                    {
                        Roles.AddUserToRole(userProfile.Username, "premiumuser");
                        Response.Redirect("Settings.aspx");
                    }
                }
                catch (Exception e)
                {
                    Response.Write(e.ToString());
                }

            }
        }

        protected void chkVisible_CheckedChanged(object sender, EventArgs e)
        {
           // Set visibility mode
            wcf.ToggleInvisibleState(loggedInUserGUID, chkVisible.Checked);
        }
       
    }
}